package controller

import (
	"errors"
	"github.com/balance_foods/common"
	"github.com/balance_foods/global"
	"github.com/balance_foods/middleware"
	"github.com/balance_foods/model/user"
	"github.com/balance_foods/router"
	"github.com/balance_foods/utils"
	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

const prefix = "user"

type UserApi struct {
}

func init() {

	userApi := UserApi{}

	group := router.Router.Group(prefix, middleware.Cors())

	{
		group.POST("login", userApi.LoginApi)
		group.POST("register", userApi.Register)
		group.POST("userInfo", middleware.JWTAuthMiddleware(), userApi.UserInfo)

	}
}

func (UserApi) UserInfo(ctx *gin.Context) {

	uid := ctx.GetInt("uid")

	var u user.User

	u.Id = uid

	err := global.Db.First(&u).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {

		common.FailWithMessage("用户信息不存在", ctx)

		return
	}
	common.SuccessWithData(u, ctx)
	return

}

func (UserApi) LoginApi(ctx *gin.Context) {

	userLogin := user.LoginRequest{}

	err := ctx.ShouldBindJSON(&userLogin)
	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	var userMode user.User

	userMode.UserName = userLogin.UserName

	err = global.Db.Where("user_name", userLogin.UserName).First(&userMode).Error

	if errors.Is(err, gorm.ErrRecordNotFound) {

		common.FailWithMessage("账号或者密码错误", ctx)

		return

	}

	err = bcrypt.CompareHashAndPassword([]byte(userMode.Password), []byte(userLogin.Password))

	if err != nil {
		common.FailWithErr(errors.New("账号或者密码错误"), ctx)
		return
	}

	data := make(map[string]interface{})

	data["user"] = userMode

	data["token"], _ = utils.GenToken(userMode.Id)

	common.SuccessWithData(data, ctx)

}

func (UserApi) Register(ctx *gin.Context) {

	register := user.RegisterRequest{}

	err := ctx.ShouldBindJSON(&register)
	if err != nil {
		common.FailWithErr(err, ctx)
		return
	}

	var userModel = user.User{}

	userModel.UserName = register.UserName

	err = global.Db.Where("user_name", register.UserName).First(&userModel).Error

	if !errors.Is(err, gorm.ErrRecordNotFound) {

		common.FailWithErr(errors.New("用户信息已存在"), ctx)

		return

	}

	userModel.UserName = register.UserName

	hashedPassword, _ := bcrypt.GenerateFromPassword([]byte(register.Password), bcrypt.DefaultCost)

	userModel.Password = string(hashedPassword)

	userModel.Name = register.Name

	userModel.Age = register.Age

	userModel.Avatar = register.Avatar

	userModel.Height = register.Height

	userModel.Weight = register.Weight

	userModel.Sex = register.Sex

	userModel.Style = register.Style

	global.Db.Save(&userModel)

	common.SuccessWithMessage("注册成功", ctx)

	return

}
